package com.gupao.webmvc.maping;

import com.gupao.webmvc.annotion.GPRequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

public class Handler {

    public Object collector;
    public Method method;
    public Pattern pattern;
    public Map<String,Integer> paramIndexMapping;

    public Handler(Object collector, Method method, Pattern pattern) {
        this.collector = collector;
        this.method = method;
        this.pattern = pattern;
        paramIndexMapping=new HashMap<String, Integer>();
        putparamIndexMapping(method);
    }

    public void putparamIndexMapping(Method method){

        //提取方法中加了注释的参数
    Annotation[] [] pa=  method.getParameterAnnotations();

        for(int i=0;i<pa.length;i++){
            for(Annotation a:pa[i]){
                if(a instanceof GPRequestParam){
                    String paraName=((GPRequestParam)a).value();
                    if(!"".equals(paraName.trim())){
                        paramIndexMapping.put(paraName,i);

                    }

                }
            }

        }
        //提取方法中的request和response参数
        Class<?> [] parameterTypes=method.getParameterTypes();
        for(int i=0;i<parameterTypes.length;i++){
           Class<?> type= parameterTypes[i];
           if(type== HttpServletRequest.class || type== HttpServletResponse.class){
               paramIndexMapping.put(type.getName(),i);

           }

        }


    }

}
